package com.lx.upload;

import com.lx.upload.bean.UploadPropertise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@AutoConfiguration
@ComponentScan("com.lx.upload")
//  matchIfMissing = true        没有enable 默认打开
@ConditionalOnProperty(prefix = "upload", name = "enable", matchIfMissing = true)
@EnableConfigurationProperties(UploadPropertise.class)
public class UploadConfigration implements WebMvcConfigurer {

    @Autowired
    UploadPropertise propertise;

    // 静态资源映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 把图片与文档的本地路径映射到项目路径
        propertise.getConfig().values().forEach(config -> {
            String diskpath = config.getDiskpath();
            if(!diskpath.endsWith("/")){
                diskpath = diskpath +  "/";
            }
            registry.addResourceHandler(config.getWebpath())
                    .addResourceLocations("file:" + diskpath);
        });
    }
}
